package com.ktwlsoft.archivemanage.controller;

import com.ktwlsoft.archivemanage.domain.business.businessService.ArchiveUnitBusinessService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ArchiveUnitRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.EditHistory;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.archiveUnit.ArchiveUnitManageAddRequest;
import com.ktwlsoft.archivemanage.payload.archiveUnit.ArchiveUnitManageUpdateRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveEditHistoryRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "立档单位管理", description = "立档单位管理")
@RestController
@RequestMapping("/archiveUnit")
public class ArchiveUnitController {

    @Autowired
    private ArchiveUnitRepositoryService archiveUnitRepositoryService;

    @Autowired
    private ArchiveUnitBusinessService archiveUnitBusinessService;

    /**
     * 分页查询立档单位列表
     *
     * @param pn         页面号码
     * @param pageSize   每页条数
     * @param conditions 查询条件
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "查询立档单位列表")
    @ResponseBody
    @RequestMapping(value = "/findPagedList", produces = "application/json", method = RequestMethod.GET)
    public ResponseEntity<?> findPagedList(@RequestParam int pn,
                                           @RequestParam int pageSize,
                                           @ApiParam(name = "unitLevel", value = "单位层级") @RequestParam String unitLevel,
                                           @ApiParam(name = "conditions", value = "查询条件") @RequestParam(required = false) String conditions) {
        Map<String, Object> data = new HashMap<>();
        data.put("unitLevel", unitLevel);
        data.put("conditions", conditions);
        Result result = Result.ok(archiveUnitRepositoryService.findPagedList(pn, pageSize, data));
        return ResponseEntity.ok(result);
    }

    /**
     * 分页查询下级立档单位列表
     *
     * @param pn       第几页
     * @param pageSize 每页多少条
     * @param unitId   立档单位id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "查询下级立档单位列表")
    @ResponseBody
    @RequestMapping(value = "/findSubArchiveUnitList", produces = "application/json", method = RequestMethod.GET)
    public ResponseEntity<?> findSubArchiveUnitList(@RequestParam int pn,
                                                    @RequestParam int pageSize,
                                                    @ApiParam(name = "unitId", value = "立档单位id") @RequestParam Long unitId) {
        Result result = Result.ok(archiveUnitRepositoryService.findSubPagedList(pn, pageSize, unitId));
        return ResponseEntity.ok(result);
    }

    /**
     * 根据立档单位id查询所有信息
     *
     * @param unitId 立档单位id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "立档单位所有信息查询")
    @ResponseBody
    @RequestMapping(value = "/findAllInformation", produces = "application/json", method = RequestMethod.GET)
    public ResponseEntity<?> findAllInformationById(@ApiParam(name = "unitId", value = "立档单位id")
                                                    @RequestParam Long unitId) {
        Result result = archiveUnitBusinessService.findAllInformationById(unitId);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据立档单位id查询一条记录
     *
     * @param unitId 立档单位id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "立档单位详情查询")
    @ResponseBody
    @RequestMapping(value = "/findOne", produces = "application/json", method = RequestMethod.GET)
    public ResponseEntity<?> findArchiveUnitInfoById(@ApiParam(name = "unitId", value = "立档单位id") @RequestParam Long unitId,
                                                     @ApiParam(value = "单位名称") @RequestParam String unitName) {

        Result result = Result.ok(archiveUnitRepositoryService.findArchiveUnitInfoById(unitId));

        OperationRepositoryService.saveLog(result, new SaveLogRequest(
                OperationLog.OperationType.CHECK,
                "查看立档单位《" + unitName + "》",
                "立档单位",
                OperationLog.BusinessType.BUSINESS
        ));

        return ResponseEntity.ok(result);
    }

    /**
     * 新增立档单位信息
     *
     * @param request       请求数据承载对象
     * @param bindingResult 绑定结果
     * @return ResponseEntity<?>
     */
    @ApiOperation("新增立档单位信息")
    @ResponseBody
    @RequestMapping(value = "/addOne", produces = "application/json", method = RequestMethod.POST)
    public ResponseEntity<?> addArchiveUnitInfo(@Validated ArchiveUnitManageAddRequest request,
                                                BindingResult bindingResult) {
        Result result = null;
        if (bindingResult.hasErrors()) {
            result = Result.body(request, ResultType.CHECK_ERROR);
            result.withMessage(bindingResult.getFieldError().getDefaultMessage());
            return ResponseEntity.ok(result);
        }
        result = archiveUnitBusinessService.addArchiveUnitInfo(request);

        OperationRepositoryService.saveLog(result, new SaveLogRequest(
                OperationLog.OperationType.ADD,
                "添加立档单位《" + request.getArchiveUnitAddRequest().getUnitName() + "》",
                "立档单位",
                OperationLog.BusinessType.BUSINESS
        ));

        return ResponseEntity.ok(result);
    }

    /**
     * 更新立档单位信息
     *
     * @param request
     * @param bindingResult
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "更新立档单位信息")
    @ResponseBody
    @RequestMapping(value = "/updateOne", produces = "application/json", method = RequestMethod.POST)
    public ResponseEntity<?> updateArchiveUnitInfo(@Validated ArchiveUnitManageUpdateRequest request,
                                                   BindingResult bindingResult) {
        Result result = null;
        if (bindingResult.hasErrors()) {
            result = Result.body(request, ResultType.CHECK_ERROR);
            result.withMessage(bindingResult.getFieldError().getDefaultMessage());
            return ResponseEntity.ok(result);
        }
        result = archiveUnitBusinessService.updateArchiveUnitInfo(request);

        OperationRepositoryService.saveLog(result, new SaveLogRequest(
                OperationLog.OperationType.EDIT,
                "编辑立档单位《" + request.getArchiveUnitUpdateRequest().getUnitName() + "》",
                "立档单位",
                OperationLog.BusinessType.BUSINESS
        ), new SaveEditHistoryRequest(
                request.getOldValue(),
                request.getNewValue(),
                EditHistory.BusinessFrom.EDIT_ARCHIVE_UNIT,
                request.getArchiveUnitUpdateRequest().getUnitId()
        ));

        return ResponseEntity.ok(result);
    }

    /**
     * 删除立档单位信息
     *
     * @param unitId 立档单位id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "删除立档单位信息")
    @ResponseBody
    @RequestMapping(value = "/deleteOne", produces = "application/json", method = RequestMethod.GET)
    public ResponseEntity<?> deleteArchiveUnitInfo(@ApiParam(name = "unitId", value = "立档单位id") @RequestParam Long unitId,
                                                   @ApiParam(name = "businessId", value = "业务编号") @RequestParam Long businessId,
                                                   @ApiParam(value = "单位名称") @RequestParam String unitName) {
        Result result = archiveUnitBusinessService.deleteArchiveUnitInfo(unitId, businessId);

        OperationRepositoryService.saveLog(result, new SaveLogRequest(
                OperationLog.OperationType.DELETE,
                "删除立档单位《" + unitName + "》",
                "立档单位",
                OperationLog.BusinessType.BUSINESS
        ));

        return ResponseEntity.ok(result);
    }

    /**
     * 注册字符串转成日期的编辑器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @ApiOperation(value = "立档单位下拉查询",tags = "1.2")
    @ResponseBody
    @GetMapping("findListAll")
    public ResponseEntity<?> findListAll(@ApiParam(name = "keyWords", value = "关键字") @RequestParam(defaultValue = "", required = false) String keyWords) {
        return ResponseEntity.ok(archiveUnitBusinessService.findListAll(keyWords));
    }
}
